package com.security.springboot.controller;


import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController()
public class TestController {
    @RequestMapping(value = "/r/r1",produces = "text/plain;charset=UTF-8")
    @PreAuthorize("hasAnyRole('r1')")
    public String r1(){
        return "访问资源1";
    }

    @RequestMapping(value = "/r/r2",produces = "text/plain;charset=UTF-8")
    @PreAuthorize("hasAnyRole('r2')")
    public String r2(){
        return "访问资源2";
    }

    @RequestMapping(value = "/getUser",produces = "application/json;charset=UTF-8")
    public String getUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        if(username.equals("anonymousUser")){
            username = "匿名用户";
        }
        return "{\"username\":\""+ username +"\"}";
    }
}
